package com.zm.exam.springbootexam.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;

import com.zm.exam.springbootexam.biz.BizException;
import com.zm.exam.springbootexam.biz.PaperBiz;
import com.zm.exam.springbootexam.entry.Paper;
import com.zm.exam.springbootexam.entry.Question;
import com.zm.exam.springbootexam.entry.Result;
import com.zm.exam.springbootexam.entry.User;
import com.zm.exam.springbootexam.mapper.PaperMapper;
import com.zm.exam.springbootexam.mapper.QuestionMapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zm
 * @since 2024-08-14
 */
@RestController
@RequestMapping("/paper")
public class PaperController {
    @Autowired
    PaperBiz paperBiz;

    @RequestMapping("add")
    public Result add(@RequestBody Paper paper, @SessionAttribute User myinfo){
        System.out.println("paper = " + paper);
        //TODO表单验证

        paper.setCreateUid(myinfo.getId());
        try {
            paperBiz.create(paper);
        } catch (BizException e) {
            return new Result(0,"考卷提交失败！",null);
        }
        return new Result(1,"考卷提交成功！",null);
    }

    @Autowired
    PaperMapper paperMapper;

    @RequestMapping("query")
    public Page<Paper> query(@RequestBody Paper paper,
                             @RequestParam(defaultValue = "1") int current,
                             @RequestParam(defaultValue = "5") int size){
        LambdaQueryWrapper<Paper> lqw = new LambdaQueryWrapper<>();
        if (paper.getTitle()!=null && paper.getTitle().isBlank() == false){
            lqw.like(Paper::getTitle,paper.getTitle());
        }
        Page<Paper> p = new PageDTO<>(current,size);
        return paperMapper.selectPage(p,lqw);

    }

    @RequestMapping("get")
    public Paper findById(int id){
        return paperMapper.findById(id);
    }

    @Autowired
    QuestionMapper questionMapper;
    @RequestMapping("auto")
    public Result auto(@RequestBody Auto auto){
        System.out.println("auto = " + auto);
        List<Question> questions = new ArrayList<>();
        questions.addAll(questionMapper.randSelectByType("填空题",auto.getCourse(), auto.getCompletion()));
        questions.addAll(questionMapper.randSelectByType("单选题",auto.getCourse(), auto.getSingle()));
        questions.addAll(questionMapper.randSelectByType("多选题",auto.getCourse(), auto.getMultiple()));
        questions.addAll(questionMapper.randSelectByType("判断题",auto.getCourse(), auto.getJudge()));
        return new Result(1,"生成成功！",questions);
    }

}
@Data
class Auto{
    private int completion;
    private int single;
    private int multiple;
    private int judge;
    private String course;
}

